package com.cskaoyan.wx.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.UserUtils;
import com.cskaoyan.wx.bean.Checkout;
import com.cskaoyan.wx.bean.CouponCount;
import com.cskaoyan.wx.bo.CartDeleteBO;
import com.cskaoyan.wx.bo.CartUpdateBO;
import com.cskaoyan.wx.bo.ChooseOrDeleteGoods;
import com.cskaoyan.wx.vo.CartIndexVO;
import com.cskaoyan.wx.vo.CheckoutVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WxCartServiceImpl implements WxCartService {


    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CartMapper cartMapper1;
    @Autowired
    CouponMapper couponMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public CartIndexVO getCartList(Integer uer_id) {
        CartIndexVO cartIndexVO = getCartIndexVO(uer_id);
        return cartIndexVO;
    }

    private CartIndexVO getCartIndexVO(Integer uer_id) {
        List<CartIndexVO.CartListBean> cartIndexVOBean = cartMapper1.getCartList(uer_id);
        //计算总共价格  总共数量  勾选的总共数量  总共价格
        int goodsCount = 0;//总共货物数量
        int checkedGoodsCount = 0;//勾选的货物数量
        Double goodsAmount = 0.0;//总共价格
        Double checkedGoodsAmount = 0.0;//勾选的货物价格
        for (CartIndexVO.CartListBean cartListBean : cartIndexVOBean) {
            Double price = cartListBean.getPrice();
            int number = cartListBean.getNumber();
            Boolean checked = cartListBean.getChecked();
            Double total = price * number;
            goodsCount += number;
            goodsAmount += total;
            if (checked) {//勾选了就要计算
                checkedGoodsAmount += total;
                checkedGoodsCount += number;
            }
        }
        CartIndexVO.CartTotalBean cartTotalBean = new CartIndexVO.CartTotalBean();
        cartTotalBean.setGoodsCount(goodsCount);
        cartTotalBean.setCheckedGoodsCount(checkedGoodsCount);
        cartTotalBean.setGoodsAmount(goodsAmount);
        cartTotalBean.setCheckedGoodsAmount(checkedGoodsAmount);

        CartIndexVO cartIndexVO = new CartIndexVO();
        cartIndexVO.setCartList(cartIndexVOBean);
        cartIndexVO.setCartTotal(cartTotalBean);
        return cartIndexVO;
    }

    @Override
    public CartIndexVO cartChecked(ChooseOrDeleteGoods chooseOrDeleteGoods) {
        Date date = new Date();
        chooseOrDeleteGoods.setUpdateTime(date);
        cartMapper1.updateInfo(chooseOrDeleteGoods);
        Integer userId = UserUtils.getUserId();
        CartIndexVO cartIndexVO = getCartIndexVO(userId);
        return cartIndexVO;
    }

    @Override
    public CartIndexVO cartDelete(CartDeleteBO cartDeleteBO) {
        Integer userId = UserUtils.getUserId();

        cartMapper1.updateDeleteCart(cartDeleteBO);

        CartIndexVO cartIndexVO = getCartIndexVO(userId);
        return cartIndexVO;
    }

    @Override
    public Integer goodsCount(Integer userId) {
        Integer count = cartMapper1.goodsCount(userId);
        return count;
    }

    @Override
    public Integer addCart(Cart cart) {
        Integer userId = addSort(cart);
        Integer count2 = cartMapper1.goodsCount(userId);
        return count2;
    }

    public Integer addSort(Cart cart) {
        Integer userId = UserUtils.getUserId();
        cart.setUserId(userId);
        int count = cartMapper1.upsert(cart);
        if (count == 1) {
            Cart cart1 = cartMapper1.getCart(cart);
            Date date = new Date();
            cart1.setAddTime(date);
            cart1.setUpdateTime(date);
            cart1.setChecked(true);
            cart1.setDeleted(false);
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andProductIdEqualTo(cart.getProductId());
            criteria.andUserIdEqualTo(userId);
            cartMapper1.updateByExampleSelective(cart1, cartExample);
        }

        return userId;
    }

    @Override
    public void cartUpdate(CartUpdateBO cartUpdateBO) {
        cartMapper1.cartUpdate(cartUpdateBO);
    }

    @Override
    public CheckoutVO checkout(Checkout checkout) {

        CheckoutVO checkoutVO = new CheckoutVO();
        //获取一个用户有多少张优惠券
        Integer userId = UserUtils.getUserId();
        Integer length = cartMapper1.getCouponLength(userId);
        Double freightPrice;//运费
        //cartId != 0  直接快速付款  根据cartId付款款
        Session session = SecurityUtils.getSubject().getSession();
        List<Cart> checkedGoodsListBeans ;
        if (checkout.getCartId() != 0) {
            CartUpdateBO cartUpdateBO = (CartUpdateBO) session.getAttribute("cart_" + checkout.getCartId());

            checkedGoodsListBeans = new ArrayList<>();
            Cart e = new Cart();

            GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(cartUpdateBO.getProductId());
            Goods goods = goodsMapper.selectByPrimaryKey(cartUpdateBO.getGoodsId());
            e.setGoodsId(cartUpdateBO.getGoodsId());
            e.setProductId(cartUpdateBO.getProductId());
            e.setNumber(cartUpdateBO.getNumber());
            e.setGoodsName(goods.getName());
            e.setPicUrl(goods.getPicUrl());
            e.setSpecifications(goodsProduct.getSpecifications());
            e.setPrice(goodsProduct.getPrice().doubleValue());
            checkedGoodsListBeans.add(e);
        }
        else {
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andUserIdEqualTo(userId);
            criteria.andCheckedEqualTo(true);
             checkedGoodsListBeans =  cartMapper1.selectByExample(cartExample);
        }




        //cartId = 0   购物车这里付款的  根据checked来选中要付款的商品
        Address address = null;
        if (checkout.getAddressId() == null || checkout.getAddressId() == 0) {
            AddressExample addressExample = new AddressExample();
            AddressExample.Criteria criteria = addressExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andIsDefaultEqualTo(true);
            List<Address> addresses = addressMapper.selectByExample(addressExample);
            for (Address address1 : addresses) {
                address = address1;
            }
            //address = addresses.get(0);
        } else {
            address = addressMapper.selectByPrimaryKey(checkout.getAddressId());
        }

        checkoutVO.setCheckedGoodsList(checkedGoodsListBeans);
        //获得优惠券所有的信息
         Coupon coupon = couponMapper.selectByPrimaryKey(checkout.getCouponId());
        //获得总共的价格 orderTotalPrice


        Double goodsTotalPrice =0.0;
        for (Cart checkedGoodsListBean : checkedGoodsListBeans) {

            int number = checkedGoodsListBean.getNumber();
            Double price = checkedGoodsListBean.getPrice();
            goodsTotalPrice += number * price;
        }
        //获取coupon的优惠额度
        Double couponValue = getaDouble(checkedGoodsListBeans, coupon, goodsTotalPrice);

        //去查运费钱  满88包邮  不满8元就付8元
        Double freigtMin = cartMapper1.getFreigtMin();
        Double freight = cartMapper1.getFreigt();
        if (goodsTotalPrice >= freigtMin) {

            freightPrice = 0.0;
        } else {
            freightPrice = freight;
        }

        Double orderTotalPrice = goodsTotalPrice + freightPrice;
        Double actualPrice = orderTotalPrice - couponValue;
        //将数据都塞到VO中返回
        checkoutVO.setCheckedAddress(address);
        checkoutVO.setCouponPrice(couponValue);
        checkoutVO.setActualPrice(actualPrice);
        checkoutVO.setOrderTotalPrice(orderTotalPrice);
        checkoutVO.setAvailableCouponLength(length);

        if (checkout.getCouponId() == 0){
            checkoutVO.setCouponId(-1);
        }else {
            checkoutVO.setCouponId(checkout.getCouponId());
        }
        checkoutVO.setFreightPrice(freightPrice);
        checkoutVO.setGoodsTotalPrice(goodsTotalPrice);
        checkoutVO.setAddressId(checkout.getAddressId());


        //orderTotalPrice:goodsTotalPrice + freightPrice    goodsTotalPrice = 商品数量 * 单价
        session.setAttribute("freightPrice",freightPrice);
        session.setAttribute("orderTotalPrice",orderTotalPrice);
        session.setAttribute("goodsTotalPrice",goodsTotalPrice);
        session.setAttribute("couponPrice",couponValue);
        session.setAttribute("checkedGoodsListBeans" , checkedGoodsListBeans);
        return checkoutVO;
    }

    private Double getaDouble(List<Cart> checkedGoodsListBeans, Coupon coupon, Double goodsTotalPrice) {
        //判断是否可以使用优惠券  ①是否过期（判断优惠券状态）  ② 是否符合使用类型
        //是否符合使用类
        Double couponValue = 0.0;
        if (coupon != null) {
            Integer goodsType = coupon.getGoodsType().intValue();
            Integer[] goodsValue = coupon.getGoodsValue();
            //限制类目  去查goods的类目
            //找出优惠券能使用的类目
            //遍历cart 依次根据goodsid 去goods表找对应的id  , 再查数据库找到categoryid  如果能找到就代表可以使用
            Outer:
            for (Cart checkedGoodsListBean : checkedGoodsListBeans) {
                Integer goodsId = checkedGoodsListBean.getGoodsId();
                if (goodsType.equals(1)) {// 优惠券的类型为1 如果是1则是类目集合
                    //遍历优惠券能使用的类目是否有和categoryId相同的
                    Integer categoryId = cartMapper1.getCategoryId(goodsId);
                    for (Integer integer : goodsValue) {
                        if (integer.equals(categoryId)  ) {//有相同直接跳出代表可以使用
                            couponValue = coupon.getDiscount().doubleValue();
                            break Outer;
                        }
                    }
                } else if (goodsType.equals(2)) {  //商品集合
                    for (Integer integer : goodsValue) {
                        if (integer.equals(goodsId)) {
                            couponValue = coupon.getDiscount().doubleValue();
                            break Outer;
                        }
                    }
                } else {//全场通用
                    couponValue = coupon.getDiscount().doubleValue();
                    break;
                }
            }
            //走到这里获得了优惠券的折扣
            //判断是否符合满减
            if (goodsTotalPrice < coupon.getMin().doubleValue()) {
                couponValue = 0.0;
            }
        }

        return couponValue;
    }
}
